package com.example.enjoyfood

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.GridView
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import android.widget.BaseAdapter
import android.view.View
import android.view.ViewGroup

class AvatarSelectionActivity : AppCompatActivity() {

    private val avatarResIds = arrayOf(
        R.drawable.avatar1, R.drawable.avatar2, R.drawable.avatar3,
        R.drawable.avatar4, R.drawable.avatar5, R.drawable.avatar6,
        R.drawable.avatar7, R.drawable.avatar8, R.drawable.avatar9,
        R.drawable.avatar10, R.drawable.avatar11, R.drawable.avatar12,
        R.drawable.avatar13, R.drawable.avatar14, R.drawable.avatar15,
        R.drawable.avatar16, R.drawable.avatar17, R.drawable.avatar18,
    )

    private var selectedAvatarResId: Int = R.drawable.default_avatar

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_avatar_selection)

        val avatarGrid = findViewById<GridView>(R.id.avatar_grid)
        val saveButton = findViewById<Button>(R.id.save_button)
        val backButton = findViewById<Button>(R.id.back_button)

        avatarGrid.adapter = AvatarAdapter(avatarResIds)

        avatarGrid.setOnItemClickListener { _, _, position, _ ->
            selectedAvatarResId = avatarResIds[position]
        }

        saveButton.setOnClickListener {
            saveAvatar()
        }

        backButton.setOnClickListener {
            finish()
        }
    }

    private fun saveAvatar() {
        val intent = Intent()
        intent.putExtra("avatar_res_id", selectedAvatarResId)
        setResult(Activity.RESULT_OK, intent)
        finish()
    }

    private inner class AvatarAdapter(private val avatars: Array<Int>) : BaseAdapter() {

        override fun getCount(): Int {
            return avatars.size
        }

        override fun getItem(position: Int): Any {
            return avatars[position]
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
            val imageView: ImageView
            if (convertView == null) {
                imageView = ImageView(this@AvatarSelectionActivity)
                imageView.layoutParams = ViewGroup.LayoutParams(300, 300)
                imageView.scaleType = ImageView.ScaleType.CENTER_CROP
            } else {
                imageView = convertView as ImageView
            }
            imageView.setImageResource(avatars[position])
            return imageView
        }
    }
}